package cn.wzl.tanks.abstractfactory;

import cn.wzl.tanks.*;

import java.awt.*;

/**
 * @author weiZhiLin
 * @version 1.0
 * @date 2021/6/8 20:44
 */
public class YellowBullet extends BaseBullet {


    public YellowBullet(int x, int y, Dir dir, Frame frame, Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.frame = (TankFrame) frame;
        this.group = group;
        fixImg();
        ((TankFrame) frame).bList.add(this);
    }

    public void paint(Graphics g) {
        // 防止内存泄漏删除子弹
        if (!living) {
            frame.bList.remove(this);
        }
        g.setColor(Color.yellow);
        g.fillRect(x, y, 10, 10);
        move();
    }

    private void move() {
        switch (dir) {
            case DOWN:
                y += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
        }
        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) {
            living = false;
        }
    }

    // 更正子弹位置
    private void fixImg() {
        this.x = x + BaseTank.WIDTH / 2 - BaseBullet.WIDTH / 2;
        this.y = y + BaseTank.HEIGHT / 2 - BaseBullet.HEIGHT / 2;
    }

    // 碰撞检测
    public void checkCash(BaseTank tank) {
        if (group == tank.getGroup()) {
            return;
        }
        Rectangle rectangle = new Rectangle(this.x, this.y, WIDTH, HEIGHT);
        Rectangle rectangle2 = new Rectangle(tank.getX(), tank.getY(), tank.WIDTH, tank.HEIGHT);
        // 是否有交集
        if (rectangle.intersects(rectangle2)) {
            this.living = false;
            tank.setLiving(false);
            frame.badTanks.remove(tank);
            // 爆炸
            int bX = tank.getX();
            int bY = tank.getY();
            this.frame.booms.add(new Boom(bX, bY, this.frame));
        }
    }
}
